import { makeAutoObservable } from "mobx";

class AppleStore {
  apples = [
    {
      id: 1,
      weight: 201,
      isEaten: false
    },
    {
      id: 2,
      weight: 222,
      isEaten: false
    },
    {
      id: 3,
      weight: 231,
      isEaten: false
    }
  ];

  newAppleId = 4;
  isPicking = false;

  constructor() {
    makeAutoObservable(this);
  }

  get appleStatus() {
    let result = {
      eaten: {
        quantity: 0,
        weight: 0
      },
      notEaten: {
        quantity: 0,
        weight: 0
      }
    }
    this.apples.forEach(apple => {
      let key = apple.isEaten ? 'eaten' : 'notEaten';
      result[key].quantity++;
      result[key].weight += apple.weight;
    })
    return result;
  }

  eatApple = (id) => {
    const apple = this.apples.find(i => i.id === id);
    apple.isEaten = true
  }

  pickApple = () => {
    if (this.isPicking) return

    this.isPicking = true;
    mockPickApple().then(() => {
      this.isPicking = false;
      this.apples.push({
        id: this.newAppleId++,
        weight: Math.floor(200 + Math.random() * 100),
        isEaten: false
      });
    });
  }
}

function mockPickApple() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve()
    }, 1500)
  });
}

export default new AppleStore()